//
//  YHMenuPopView.swift
//  Adorbee
//
//  Created by amovision on 2025/3/1.
//

import UIKit
#if canImport(SnapKit)
import SnapKit
#endif

public extension YHPopProperty {
  static let menuDataSource = "YHMenuDataSource"
  static let menuSelectedIndex = "YHMenuSelectedIndex"
}

public class YHMenuPopView: YHPopView {
  private lazy var selectedIndex: Int = properties?[.menuSelectedIndex] as? Int ?? -1
    
  private lazy var dataSource: [String] = properties?[.menuDataSource] as? [String] ?? []
    
  private var hasHeader: Bool {
    properties?[.header] != nil
  }

  public override var direction: YHPopViewDirection {
    .bottom
  }
  
  private let buttonColor = UIColor.dynamic(.gray("F5"), .gray("2C"))
    
  private lazy var cancel = {
    let btn = UIButton(title: AString("Cancel".local, font: .num(16), color: .label1))
    btn.set(bImage: buttonColor, state: .highlighted)
    btn.addLine(.top, 0.5, color: .black(1))
    btn.addAction(.buttonAction, target: self)
    return btn
  }()
    
  public override func initContentUI() {
    contentWidth = Self.maxPopWidth
    contentHeight = 20 + CGFloat((dataSource.count + (hasHeader ?1:0) + 1))*50 + YHSafeBottomHeight
    if hasHeader {
      let label = UILabel(properties?[.header], font: .num(16, .bold), color: .label, aligment: .center)
#if canImport(SnapKit)
      label.makeConstraints(on: contentView) { make in
        make.left.equalTo(30)
        make.right.equalTo(-30)
        make.top.equalTo(0)
        make.height.equalTo(50)
      }
#endif
    }
    for (idx, item) in dataSource.enumerated() {
      let title = AString.strings(item, fonts: UIFont.num(16), colors: [UIColor.label, Theme.light, Theme.light])
      let btn = UIButton(
        titles: title,
        bImages: [UIColor.clear, buttonColor, buttonColor],
        states: [.normal, .highlighted, .selected]
      )
      btn.isSelected = idx == selectedIndex
      btn.tag = idx + 100
      btn.addAction(.buttonAction, target: self)
      contentView.addSubview(btn)
#if canImport(SnapKit)
      btn.snp.makeConstraints { make in
        make.left.right.equalTo(0)
        make.top.equalTo((hasHeader ?60 : 10) + CGFloat(idx)*50)
        make.height.equalTo(50)
      }
#endif
    }
#if canImport(SnapKit)
    cancel.makeConstraints(on: contentView) { make in
      make.bottom.equalTo(-YHSafeBottomHeight)
      make.left.right.equalTo(0)
      make.height.equalTo(50)
    }
#endif
  }

  @objc private func buttonAction(_ btn: UIButton) {
    if btn == cancel { dismiss() }
    else {
      let index = btn.tag - 100
      guard selectedIndex != index else { return }
      dismiss(index)
    }
  }
}
